package com.itheima.reggie.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomerException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Category;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.CategoryMapper;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.CategoryService;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestParam;

import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {

    @Autowired
    private SetmealDishService setmealDishService;


    @Override
    /**
     * 新增套餐，同时保存套餐和菜品的关联关系
     */
    @Transactional
    public void saveWithDish(SetmealDto setmealDto) {
        //保存套餐基本信息
        this.save(setmealDto);

        //保存套餐和菜品的基本信息
        List<SetmealDish> list = setmealDto.getSetmealDishes();
        list.stream().map((item)->{
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());

        setmealDishService.saveBatch(list);
    }

    /**
     * 删除套餐
     * @param
     */
    @Override
    @Transactional
    public void removeWithDish(List<Long> ids) {

        //1. 先查询该套餐是否停售
        LambdaQueryWrapper<Setmeal> lambdaQueryWrapper1=new LambdaQueryWrapper<>();
            // 1.2查询是否停售
        lambdaQueryWrapper1.in(Setmeal::getId,ids);
        lambdaQueryWrapper1.eq(Setmeal::getStatus,1);
        int count = this.count(lambdaQueryWrapper1);
        if(count>0){
            //说明该套餐正在销售，不能删除
            throw new CustomerException("该套餐正在销售，不能删除");
        }

        //2.已经停售了，直接删除
        this.removeByIds(ids);

        //3.删除关联表数据setmeal_dish
        LambdaQueryWrapper<SetmealDish> lambdaQueryWrapper2=new LambdaQueryWrapper<>();
        lambdaQueryWrapper2.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lambdaQueryWrapper2);

    }
}
